import { createRouter, createWebHistory } from 'vue-router'

import index from './components/index.vue'
import login from './components/login/login.vue'
import register from './components/login/register.vue'
import menusList from './components/menus/list.vue'
import menusAdd from './components/menus/add.vue'

// 创建路由实例对象
const router = createRouter({
    history: createWebHistory(),
    routes: [
        { path: '/', name:'index',component:index ,
            children:[
                {
                    path: 'menus/list',component:menusList,
                },
                {
                    path: 'menus/add',component:menusAdd,
                },
                {
                    path: 'users/list',component:() => import('./components/users/list.vue'),
                },
                {
                    path: 'users/add',component:() => import('./components/users/add.vue'), props: route => ({ id: route.query.id })
                },
            ]
        },
        { path: '/login', name:'login',component:login },
        { path: '/register', name:'register',component:register },
    ],
})


// 全局路由导航守卫
router.beforeEach((to, from, next) => {

    // 判断用户访问的是否为登录页
    if (to.path === '/login' || to.path==='/register') return next()
    // 获取 token 值
    const loginToken = localStorage.getItem('token')

    if (!loginToken) {
        next('/login')
    } else {
        next()
    }
})


export default router
